package com.itheima.bakery.demos.web.controller;

import com.itheima.bakery.demos.web.Repositories.*;
import com.itheima.bakery.demos.web.model.*;
import com.itheima.bakery.demos.web.service.CartService;
import com.itheima.bakery.demos.web.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/cart")
public class CartController {

    @Autowired
    private CartService cartService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CartItemRepository cartItemRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ProductRepository productRepository;

    private static final Logger logger = LoggerFactory.getLogger(CartController.class);
    @PostMapping("/add")
    @Transactional
    public ResponseEntity<?> addToCart(@RequestParam Integer userId,
                                       @RequestParam Integer productId,
                                       @RequestParam Integer quantity,
                                       HttpSession session) {
        try {
            User user = userRepository.findById(userId)
                    .orElseThrow(() -> new IllegalArgumentException("User with ID " + userId + " does not exist."));
            Product product = productRepository.findById(productId)
                    .orElseThrow(() -> new RuntimeException("Product not found with ID: " + productId));

            ArrayList<CartItem> cart = (ArrayList<CartItem>) session.getAttribute("cart");
            if (cart == null) {
                cart = new ArrayList<>();
                session.setAttribute("cart", cart);
            }

            CartItem existingItem = cart.stream()
                    .filter(item -> item.getProductId().equals(productId))
                    .findFirst()
                    .orElse(null);

            if (existingItem != null) {
                existingItem.setQuantity(existingItem.getQuantity() + quantity);
            } else {
                CartItem newItem = new CartItem();
                newItem.setUser(user);
                newItem.setProduct(product);
                newItem.setQuantity(quantity);
                cart.add(newItem);
                cartItemRepository.save(newItem);
            }

            session.setAttribute("cart", cart);

            Map<String, String> responseMap = new HashMap<>();
            responseMap.put("message", "Item added to cart successfully");
            return ResponseEntity.ok(responseMap);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    @GetMapping("/items")
    public ResponseEntity<?> getCartItemsFromService(@RequestParam Integer userId, HttpSession session) {
        try {
            List<CartItem> cartItems = cartService.getCartItems(userId, session);
            return ResponseEntity.ok(cartItems);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("Error fetching cart items");
        }
    }

    @PostMapping("/clear")
    @Transactional
    public ResponseEntity<?> clearCart(@RequestParam Integer userId, HttpSession session) {
        cartService.clearCart(userId, session);
        return ResponseEntity.ok("Cart cleared successfully");
    }

    @PostMapping("/checkout")
    @Transactional
    public ResponseEntity<?> checkout(@RequestBody CheckoutRequest request) {
        try {
            Integer userId = request.getUserId();
            List<Integer> cartItemIds = request.getCartItemIds(); // 确保这是购物车项 ID 列表
            // 输出接收到的 userId、cartItems 信息
            logger.info("Received userId: {}", userId);
            logger.info("Received cartItems: {}", cartItemIds);
            // 根据传递的购物车项 ID 查询具体的购物车项
            List<CartItem> cartItems = cartItemIds.stream()
                    .map(id -> cartItemRepository.findById(id)) // 直接使用 findById 方法
                    .filter(Optional::isPresent)
                    .map(Optional::get)
                    .collect(Collectors.toList());



            if (cartItems == null || cartItems.isEmpty()) {
                logger.warn("No items to checkout");
                return ResponseEntity.badRequest().body("没有要结账的商品项");
            }

            // 执行结账逻辑，使用查询到的 cartItems
            Integer orderId = orderService.createOrderAndDetails(userId, cartItems);
            if (orderId == null) {
                logger.error("Order creation failed");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("订单创建失败");
            }

            // 创建响应Map
            Map<String, String> responseMap = new HashMap<>();
            responseMap.put("message", "Checkout successful");
            responseMap.put("orderId", String.valueOf(orderId));

            // 构建JSON响应
            logger.info("Checkout successful, orderId: {}", orderId);
            return ResponseEntity.ok(responseMap);
        } catch (Exception e) {
            logger.error("Error during checkout: ", e);
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }


    @PostMapping("/check")
    public ResponseEntity<Map<String, Boolean>> checkProductInCart(
            @RequestParam("userId") Integer userId,
            @RequestParam("productId") Integer productId) {

        boolean exists = cartService.isProductInCart(userId, productId);
        Map<String, Boolean> response = new HashMap<>();
        response.put("exists", exists);
        return ResponseEntity.ok(response);
    }

    @PostMapping("/update")
    @Transactional
    public ResponseEntity<Map<String, Object>> updateCartItemQuantity(@RequestParam Integer userId,
                                                                      @RequestParam Integer cartItemId,
                                                                      @RequestParam Integer newQuantity,
                                                                      HttpSession session) {
        try {
            CartItem cartItem = cartItemRepository.findById(cartItemId)
                    .orElseThrow(() -> new RuntimeException("CartItem with ID " + cartItemId + " does not exist."));

            if (!cartItem.getUser().getUserID().equals(userId)) {
                throw new RuntimeException("CartItem does not belong to User with ID: " + userId);
            }

            if (newQuantity < 0) {
                throw new RuntimeException("New quantity cannot be negative.");
            }

            cartItem.setQuantity(newQuantity);
            if (newQuantity == 0) {
                cartItemRepository.delete(cartItem);
            } else {
                cartItemRepository.save(cartItem);
            }

            synchronized (session) {
                List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
                if (cart != null) {
                    for (CartItem item : cart) {
                        if (item.getId().equals(cartItemId)) {
                            item.setQuantity(newQuantity);
                            break;
                        }
                    }
                }
                session.setAttribute("cart", cart);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "Cart item quantity updated successfully");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", "Error updating cart item quantity: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    @PostMapping("/update-quantity")
    public ResponseEntity<Map<String, Object>> updateQuantity(
            @RequestParam Integer userId,
            @RequestParam Integer productId,
            @RequestParam Integer quantity) {
        cartService.updateCartItemQuantity(userId, productId, quantity);


        Map<String, Object> response = new HashMap<>();
        response.put("message", "Quantity updated successfully");
        response.put("userId", userId);
        response.put("productId", productId);
        response.put("quantity", quantity);

        return ResponseEntity.ok(response);
    }

    @DeleteMapping("/delete")
    public ResponseEntity<String> deleteCartItem(@RequestParam Integer userId,
                                                 @RequestParam Integer cartItemId) {
        Optional<CartItem> cartItemOptional = cartItemRepository.findByUser_IdAndId(userId, cartItemId);

        if (cartItemOptional.isPresent()) {
            CartItem cartItem = cartItemOptional.get();
            cartItemRepository.delete(cartItem);
            return ResponseEntity.ok("CartItem deleted successfully");
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}